import React from 'react';
import { Tour, TourProps, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import type { ReactNode } from 'react';

// 确保CommonTourStep接口包含title和description等必需属性
interface CommonTourStep {
  key: string;
  title: string;
  description: string;
  placement?: 'top' | 'bottom' | 'left' | 'right';
}

interface CommonTourProps {
  open: boolean;
  onClose: () => void;
  steps: CommonTourStep[];
  targetRefs: { [key: string]: any };
  mask?: boolean;
  arrow?: boolean;
  type?: 'default' | 'primary';
}

const CommonTour: React.FC<CommonTourProps> = ({
  open,
  onClose,
  steps,
  targetRefs,
  mask = true,
  arrow = true,
  type = 'primary',
}) => {
  // 处理target函数，添加安全检查
  const processedSteps: TourProps['steps'] = steps.map(step => ({
    ...step,
    target: () => {
      const ref = targetRefs[step.key];
      if (ref?.current && ref.current instanceof HTMLElement) {
        return ref.current;
      }
      return null;
    },
  }));

  return (
    <Tour
      open={open}
      onClose={onClose}
      steps={processedSteps}
      mask={mask}
      arrow={arrow}
      type={type}
      placement="right"
    />
  );
};

// Tour引导按钮组件
export const TourGuideButton: React.FC<{
  onClick: () => void;
  title?: string;
  icon?: ReactNode;
  style?: React.CSSProperties;
}> = ({ onClick, title = '显示使用引导', icon, style }) => {
  return (
    <Tooltip title={title}>
      <span
        onClick={onClick}
        style={{
          cursor: 'pointer',
          fontSize: 20,
          marginLeft: 10,
          ...style,
        }}
      >
        {icon || <QuestionCircleOutlined />}
      </span>
    </Tooltip>
  );
};

export default CommonTour;